part of auth_card;

class _LoginCard extends StatefulWidget {
  _LoginCard(
      {Key? key,
      this.loadingController,
      required this.userValidator,
      required this.passwordValidator,
      required this.onSwitchRecoveryPassword,
      required this.userType,
      this.onSwitchAuth,
      this.onSubmitCompleted,
      this.hideForgotPasswordButton = false,
      this.hideSignUpButton = false,
      this.loginAfterSignUp = true,
      this.hideProvidersTitle = false})
      : super(key: key);

  final AnimationController? loadingController;
  final FormFieldValidator<String>? userValidator;
  final FormFieldValidator<String>? passwordValidator;
  final Function onSwitchRecoveryPassword;
  final Function? onSwitchAuth;
  final Function? onSubmitCompleted;
  final bool hideForgotPasswordButton;
  final bool hideSignUpButton;
  final bool loginAfterSignUp;
  final bool hideProvidersTitle;
  final LoginUserType userType;

  @override
  _LoginCardState createState() => _LoginCardState();
}

class _LoginCardState extends State<_LoginCard> with TickerProviderStateMixin {
  final GlobalKey<FormState> _formKey = GlobalKey();

  final _passwordFocusNode = FocusNode();
  final _confirmPasswordFocusNode = FocusNode();

  TextEditingController? _nameController;
  TextEditingController? _passController;
  TextEditingController? _confirmPassController;

  var _isLoading = false;
  var _isSubmitting = false;
  var _showShadow = true;

  /// switch between login and signup
  late AnimationController _loadingController;
  late AnimationController _switchAuthController;
  late AnimationController _postSwitchAuthController;
  late AnimationController _submitController;

  ///list of AnimationController each one responsible for a authentication provider icon
  List<AnimationController> _providerControllerList = <AnimationController>[];


  bool get buttonEnabled => !_isLoading && !_isSubmitting;

  @override
  void initState() {
    super.initState();

    final auth = Provider.of<Auth>(context, listen: false);
    _nameController = TextEditingController(text: auth.email);
    _passController = TextEditingController(text: auth.password);
    _confirmPassController = TextEditingController(text: auth.confirmPassword);

    _loadingController = widget.loadingController ??
        (AnimationController(
          vsync: this,
          duration: Duration(milliseconds: 1150),
          reverseDuration: Duration(milliseconds: 300),
        )..value = 1.0);

    _loadingController.addStatusListener(handleLoadingAnimationStatus);

    _switchAuthController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 800),
    );
    _postSwitchAuthController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 150),
    );
    _submitController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 1000),
    );
    _providerControllerList = auth.loginProviders
        .map(
          (e) => AnimationController(
            vsync: this,
            duration: Duration(milliseconds: 1000),
          ),
        )
        .toList();
  }

  void handleLoadingAnimationStatus(AnimationStatus status) {
    if (status == AnimationStatus.forward) {
      setState(() => _isLoading = true);
    }
    if (status == AnimationStatus.completed) {
      setState(() => _isLoading = false);
    }
  }

  @override
  void dispose() {
    _loadingController.removeStatusListener(handleLoadingAnimationStatus);
    _passwordFocusNode.dispose();
    _confirmPasswordFocusNode.dispose();

    _switchAuthController.dispose();
    _postSwitchAuthController.dispose();
    _submitController.dispose();

    _providerControllerList.forEach((controller) {
      controller.dispose();
    });
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final auth = Provider.of<Auth>(context, listen: true);
    final theme = Theme.of(context);
    final deviceSize = MediaQuery.of(context).size;
    final cardWidth = min(deviceSize.width * 0.95, 360.0);
    const cardPadding = 16.0;
    final textFieldWidth = cardWidth - cardPadding * 2;
    final authForm = Form(
      key: _formKey,
      child: Column(
        children: [

          Container(
            padding: EdgeInsets.only(top: 16,bottom: 16),
            width: cardWidth,
            child: Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 10,bottom: 30),
                  child: Text(
                    '從一下方式登入',
                    style: TextStyle(
                      color: Color(0Xff2D7FC7),
                      fontSize: 17,
                      fontFamily: "SemiBold",
                    ),
                  ),
                ),
                CustomButton(
                  color1: Color(0xff93BB24),
                  color2: Color(0xff2D7FC7),
                  image: SvgImg.phone,
                  title: "手機登錄",
                  type: ButtonType.Filling,
                  onPressed: buttonEnabled
                      ? () {
                    // save state to populate email field on recovery card
                    _formKey.currentState!.save();
                    widget.onSwitchRecoveryPassword();
                  }
                      : null,
                ),
                SizedBox(height: 20),
                CustomButton(
                  color1: Color(0xff93BB24),
                  color2: Color(0xff2D7FC7),
                  image: SvgImg.wechat,
                  title: "微信登錄",
                  fontColor: Color(0xff93BB24),
                  type: ButtonType.Border,
                  onPressed: auth.weChat,
                ),
                SizedBox(height: 20),
                CustomButton(
                  color1: Color(0xff93BB24),
                  color2: Color(0xff2D7FC7),
                  image: SvgImg.facebook,
                  title: "Facebook登錄",
                  fontColor: Color(0xff2D7FC7),
                  type: ButtonType.Border,
                  onPressed: auth.facebook,
                ),

                Container(
                  margin: EdgeInsets.only(top: 20,bottom: 20),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        '還未成為會員？',
                        style: TextStyle(
                            color: Color(0Xff154D7C),
                            fontSize: 13,
                            fontFamily: "SemiBold",
                            fontWeight: FontWeight.bold),
                      ),
                      GestureDetector(
                        onTap: () {},
                        child: Text(
                          '按此註冊',
                          style: TextStyle(
                              color: Color(0Xff93BB24),
                              fontSize: 13,
                              fontFamily: "SemiBold",
                              fontWeight: FontWeight.bold),
                        ),
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );

    return FittedBox(
      child: Card(
        elevation: _showShadow ? theme.cardTheme.elevation : 0,
        child: authForm,
      ),
    );
  }
}
